<?php

namespace App\Http\Controllers\Admin;

// use App\Http\Controllers\Controller;
use App\Http\Forms\CategoryForm;
use App\Http\Forms\GoodCategoryForm;
use App\Http\Forms\GoodForm;
use App\Http\Forms\RulesForm;
use App\Library\OSS;
use App\Modules\Comment\Models\Comment;
use App\Modules\Good\Models\Good;
use App\Modules\Good\Models\GoodAttr;
use App\Modules\Good\Models\GoodAttrValue;
use App\Modules\Good\Models\GoodSpec;
use App\Modules\Good\Models\UserGoodsPoster;
use App\Modules\Package\Models\PackageAttrValue;
use App\Modules\Rebate\Models\RebateRule;
use App\Modules\Shop\GoodsList;
use App\Modules\Shop\Manager;
use App\Modules\Good\Manager as GoodManager;
use App\Modules\Shop\Models\Category;
use App\Modules\Shop\Shop;
use App\Modules\System\Models\Brand;
use App\Modules\User\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Modules\System\Models\Tag;


class GoodController extends Controller
{
    public function index(Request $request)
    {
        $this->checkAuth('merchant_staff_goods_and_package', 'good');
        $id                = $request->input('id');
        $name              = $request->input('name');
        $shopId            = $request->input('shop_id');
        $shop              = Shop::query()->get()->keyBy('id');
        $top_category_id   = $request->input('top_category_id');
        $first_category_id = $request->input('first_category_id');
        $category_id       = $request->input('category_id');
        $brand_id          = $request->input('brand_id');

        $query = Good::query()
            ->leftJoin('brands', 'brands.id', '=', 'goods.brand_id')
            ->leftJoin('categories as cate', 'cate.id', '=', 'goods.category_id')
            ->leftJoin('categories as cate_top', 'cate_top.id', '=', 'goods.top_category_id')
            ->leftJoin('categories as cate_first', 'cate_first.id', '=', 'goods.first_category_id')
            ->where('goods.shop_id', $shopId)
            ->when(!empty($brand_id), function ($query) use ($brand_id) {
                return $query->where('brand_id', $brand_id);
            })
            ->when(!is_null($id), function ($query) use ($id) {
                return $query->where('goods.id', $id);
            })
            ->when(!is_null($category_id), function ($query) use ($category_id) {
                return $query->where('goods.category_id', $category_id);
            })
            ->select('goods.*', 'brands.name as brand', 'cate.name as category_name', 'cate_top.name as top_category_name', 'cate_first.name as first_category_name')
            ->orderBy('goods.sort', 'desc')
            ->orderBy('goods.created_at', 'desc');
        if (!empty($name)) {
            $query->where('goods.name', 'like', '%' . $name . "%");
        }

        $data = $query->paginate(20);

        $shopData = Shop::query()->find($shopId);

        // 顶级分类
        $topCategory = Category::query()
                        ->whereIn('id', $shopData->category_ids ?? [])
                        ->get()
                        ->pluck('name', 'id');
        
        // 一级分类
        $firstCategory = [];
        if (!empty($first_category_id)) {
            $firstCategoryData = Category::query()
                                    ->where('top_category_id', $top_category_id)
                                    ->where('first_category_id', 0)
                                    ->where('shop_id', $shopId)
                                    ->pluck('name', 'id')
                                    ->all();
            if ($firstCategoryData) {
                foreach ($firstCategoryData as $k1 => $v1) {
                    $firstCategory[$k1] = $v1;
                }
            }
        }

        // 二级分类
        $category = [];
        $categoryData = Category::query()
                ->where('shop_id', $shopId)
                ->where('first_category_id', $first_category_id)
                ->get()
                ->pluck('name', 'id')
                ->all();
        if ($categoryData) {
            foreach ($categoryData as $k1 => $v1) {
                $category[$k1] = $v1;
            }
        }

        // 品牌
        $brand = Brand::query()
                ->where('shop_id', $shopId)
                ->where('pid', $top_category_id)
                ->get()
                ->pluck('name', 'id')
                ->all();
        
        $sidebar = 'goods';
        return view('good.index', compact('data', 'name', 'shop', 'shopId', 'id', 'category_id', 'top_category_id', 'first_category_id', 'topCategory', 'firstCategory', 'category', 'brand_id', 'brand', 'sidebar'));
    }

    public function create(Request $request)
    {
        $this->checkAuth('merchant_staff_and_package_add', 'good-add');
        $shopId = $request->input('shop_id');
        $shop = Manager::getShop();
        //获取到当前门店数据，如果当前门店中category_ids存在，
        //则根据categorys_ids获取当前门店的分类，否则按照分类名去查找分类表获取到当前分类数据
        //如果还找不到直接略过
        $shopData = Shop::query()->find($shopId);
        // 顶级分类
        $topCategory = [0 => '请选择顶级分类'];
        if ($shopData->category_ids) {
            $category = Category::query()->whereIn("id", $shopData->category_ids)->pluck('name', 'id')->all();
            foreach ($category as $key => $value) {
                $topCategory[$key] = $value;
            }
        }
        
        $form = $this->form(GoodForm::class, [
            'method' => 'PUT',
            'url' => route('admin.good.store', ['shop_id' => $shopId]),
        ], [
            'shop' => $shop->pluck('name', 'id')->all(),
            // 'category_id' => $category,
            // 'brand_id' => $brand,
            'top_category_id' => $topCategory
        ]);
        $sidebar = 'goods_detail';
        $flag = 'goods';//用于区分表单页面的js
        return view('good.form', compact('form', 'category', 'shopId', 'flag', 'sidebar'));
    }

    public function store(Request $request)
    {
        $this->checkAuth('merchant_staff_and_package_add', 'good-add');
        $shopId = $request->input('shop_id');
        $form = $this->form(GoodForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();

        $data['display_price']        = $data['display_price'] * 100;
        $data['price']                = $data['price'] * 100;
        $data['is_free']              = $data['is_free'] ?? 0;
        $data['is_balance_pay']       = $data['is_balance_pay'] ?? 0;//是否可以使用充值消费
        $data['is_recharge']          = $data['is_recharge'] ?? 0;//本商品是否为充值商品
        $data['recharge_money']       = $data['is_recharge'] ? $data['recharge_money'] * 100 : 0;//实际充值金额
        $data['need_delivery']        = 0;
        $data['status']               = Good::STATUE_OFF;
        $data['shop_id']              = $shopId;
        $data['virtual_sales_volume'] = $data['virtual_sales_volume'] ?? 0;
        $data['keywords']             = $data['keywords'] ?? '';
        // if (!empty($data['discount_type'])) {
        //     $data['discount_limit'] = $data['discount_limit'] * 100;
        //     $data['discount_amount'] = $data['discount_amount'] * 100;
        // } else {
        //     $data['discount_limit'] = null;
        //     $data['discount_amount'] = null;
        // }
            
        $data['category'] = Category::query()->find($data['top_category_id'])['name'];

        if (!empty($data['category_id'])) {
            $categoryName = Category::query()->whereIn('id', $data['category_id'])->get('name')->pluck('name')->toArray();

            $data['category_id'] = implode($data['category_id'], ',');
            $data['second_category_id'] = $data['category_id'];
            $data['second_category_name'] = implode($categoryName, ',');
        }else{
            $data['category_id'] = '';
        }
        // dd($data['category_id']);
        // $data['category_id'] = implode($data['category_id'], ',');
        // $data['second_category_id'] = $data['category_id'];
        // $data['second_category_name'] = implode($categoryName, ',');

        $data['tag_id'] = !empty($data['tag_id']) ? implode($data['tag_id'], ',') : '';
        
        /** @var Good $good */
        $good = Good::query()->create($data);
        foreach ($data['spec'] as $item) {
            $attr = GoodAttr::query()
                ->firstOrCreate([
                    'good_id' => $good->id,
                    'name' => $item['name'],
                    'sort' => $item['sort'],
                ]);
            $item['value'] = array_unique($item['value']);
            foreach ($item['value'] as $item2) {
                GoodAttrValue::query()
                    ->create([
                        'good_id' => $good->id,
                        'good_attr_id' => $attr->id,
                        'value' => $item2,
                    ]);
            }
        }
        Shop::query()->find($data['shop_id'])->increment('goods_number');
        GoodsList::addData(GoodsList::TYPE_GOOD, $good->id, $good->price, $good->sort, $good->sales_volume ?? 0, $good->created_at, $good->visitor);
        return redirect()->route('admin.good.spec.edit', ['id' => $good->id, 'shop_id' => $shopId]);
    }

    public function edit($id, Request $request)
    {
        $this->checkAuth('merchant_staff_and_package_edit', 'good-edit');
        $redirect = $request->input('redirect');
        $good = Good::query()->find($id);
        $shop = Manager::getShop();
        $good->display_price /= 100;
        $good->price /= 100;
        $good->recharge_money /= 100;
        $is_recharge = $good->is_recharge;
        //获取到当前门店数据，如果当前门店中category_ids存在，
        //则根据categorys_ids获取当前门店的分类，否则按照分类名去查找分类表获取到当前分类数据
        //如果还找不到直接略过
        $shopData = Shop::query()->find($good->shop_id);
        $topCategory = [0 => '请选择顶级分类'];
        if ($shopData->category_ids) {
            $categoryData = Category::query()->whereIn("id", $shopData->category_ids)->pluck('name', 'id')->all();
            foreach ($categoryData as $key => $value) {
                $topCategory[$key] = $value;
            }
        }
        // $firstCategory = [0 => '无'];
        $firstCategoryData = Category::query()
                                ->where('top_category_id', $good->top_category_id)
                                ->where('first_category_id', 0)
                                ->where('shop_id', $good->shop_id)
                                ->pluck('name', 'id')
                                ->all();
        // if ($firstCategoryData) {
        //     foreach ($firstCategoryData as $k1 => $v1) {
        //         $firstCategory[$k1] = $v1;
        //     }
        // }

        // dd($firstCategory);
//        $good->discount_limit = is_null($good->discount_limit)? null : $good->discount_limit/100;
//        $good->discount_amount = is_null($good->discount_amount)? null : $good->discount_amount/100;

        $attr = GoodAttr::query()->where('good_id', $id)->orderBy('sort', 'desc')->get();
        $attrValue = GoodAttrValue::query()->whereIn('good_attr_id', $attr->pluck('id')->all())->get()->groupBy('good_attr_id');
        $spec = [];
        // if ($good->top_category_id) {
        //     $category = Category::query()
        //         ->where('pid', $good->top_category_id)
        //         ->get()
        //         ->pluck('name', 'id')
        //         ->all();
        //     $brand = Brand::query()
        //         ->where('pid', $good->top_category_id)
        //         ->get()
        //         ->pluck('name', 'id')
        //         ->all();
        // } else {
        //     $pid = Category::query()->where("name", $good->category)->value("id");
        //     if (!$pid) goto BEGIN;
        //     $category = Category::query()
        //         ->where('pid', $pid)
        //         ->get()
        //         ->pluck('name', 'id')
        //         ->all();
        //     $brand = Brand::query()
        //         ->where('pid', $pid)
        //         ->get()
        //         ->pluck('name', 'id')
        //         ->all();
        // }
        // BEGIN:
        
        $brand = Brand::query()
                ->where('shop_id', $good->shop_id)
                ->where('pid', $good->top_category_id)
                ->get()
                ->pluck('name', 'id')
                ->all();
        $categoryData = Category::query()
                ->where('shop_id', $good->shop_id)
                ->where('first_category_id', $good->first_category_id)
                ->get()
                ->pluck('name', 'id')
                ->all();
        $tagData = Tag::query()
                ->where('shop_id', $good->shop_id)
                ->get()
                ->pluck('name', 'id')
                ->all();
        // if ($categoryData) {
        //     foreach ($categoryData as $k1 => $v1) {
        //         $category[$k1] = $v1;
        //     }
        // }

        // dd($shop->pluck('name', 'id')->all());

        foreach ($attr as $item) {
            $tmp['name'] = $item->name;
            $tmp['sort'] = $item->sort;
            $tmp['value'] = [];
            foreach ($attrValue->get($item->id) as $value) {
                $tmp['value'][] = $value->value;
            }
            $spec[] = $tmp;
        }
        $good->category_id = !empty($good->second_category_id) ? explode(',', $good->second_category_id) : '';
        $good->tag_id = !empty($good->tag_id) ? explode(',', $good->tag_id) : '';
        $good->spec = $spec;
        $form = $this->form(GoodForm::class, [
            'method' => "POST",
            'url' => route('admin.good.update', ['id' => $id, 'redirect' => $redirect]),
            'model' => $good,
        ], [
            'shop' => $shop->pluck('name', 'id')->all(),
            'category_id' => $categoryData,
            'brand_id' => $brand,
            'top_category_id' => $topCategory,
            'first_category_id' => $firstCategoryData,
            'tag_id' => $tagData,
        ]);
        $shopId = $good->shop_id;
        $sidebar = 'goods_detail';
        $flag = 'goods';//用于区分表单页面的js
        return view('good.form', compact('form', 'shopId', 'is_recharge', 'flag', 'sidebar'));
    }

    public function update($id, Request $request)
    {
        $this->checkAuth('merchant_staff_and_package_edit', 'good-edit');
        $redirect = $request->input('redirect');
        $form = $this->form(GoodForm::class);
        //验证器
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();

        $data['display_price']  = $data['display_price'] * 100;
        $data['price']          = $data['price'] * 100;
        $data['is_free']        = $data['is_free'] ?? 0;
        $data['is_balance_pay'] = $data['is_balance_pay'] ?? 0;//是否可以使用充值消费
        $data['is_recharge']    = $data['is_recharge'] ?? 0;//本商品是否为充值商品
        $data['recharge_money'] = $data['is_recharge'] ? $data['recharge_money'] * 100 : 0;//实际充值金额
        $data['need_delivery']  = $data['need_delivery'] ?? 0;
        $data['sort']           = $data['sort'] ?? 0;
        $data['keywords']       = $data['keywords'] ?? '';

        if (!empty($data['category_id'])) {
            $categoryName = Category::query()->whereIn('id', $data['category_id'])->get('name')->pluck('name')->toArray();

            $data['category_id'] = implode($data['category_id'], ',');
            $data['second_category_id'] = $data['category_id'];
            $data['second_category_name'] = implode($categoryName, ',');
        }else{
            $data['category_id'] = '';
        }
        
        $data['tag_id'] = !empty($data['tag_id']) ? implode($data['tag_id'], ',') : '';
        // if (!empty($data['discount_type'])) {
        //     $data['discount_limit'] = $data['discount_limit'] * 100;
        //     $data['discount_amount'] = $data['discount_amount'] * 100;
        // } else {
        //     $data['discount_limit'] = null;
        //     $data['discount_amount'] = null;
        // }
        $data['category'] = Category::query()->find($data['top_category_id'])['name'];

        $spec = $data['spec'];
        unset($data['spec']);

        Good::query()
            ->where('id', $id)
            ->update($data);
        $tmp = [];
        $sort = [];
        foreach ($spec as $value) {
            $tmp[$value['name']] = $value['value'];
            $sort[$value['name']] = $value['sort'];
        }
        $spec = $tmp;
        $attr = array_keys($spec);
        $oldAttr = GoodAttr::query()->where('good_id', $id)->get()->pluck('name', 'id')->all();
        $add = array_diff($attr, $oldAttr);
        $del = array_diff($oldAttr, $attr);
        $update = array_diff($oldAttr, $del);
        foreach ($del as $key => $value) {
            GoodAttr::query()->where('good_id', $id)->where('id', $key)->delete();
            GoodAttrValue::query()->where('good_id', $id)->where('good_attr_id', $key)->delete();
        }
        foreach ($add as $value) {
            $newAttr = GoodAttr::query()
                ->firstOrCreate([
                    'good_id' => $id,
                    'name' => $value,
                    'sort' => $sort[$value],
                ]);
            foreach ($spec[$value] as $newValue) {
                GoodAttrValue::query()
                    ->firstOrCreate([
                        'good_id' => $id,
                        'good_attr_id' => $newAttr->id,
                        'value' => $newValue,
                    ]);
            }
        }
        foreach ($update as $key => $updateValue) {
            GoodAttr::query()
                ->where('good_id', $id)
                ->where('id', $key)
                ->update([
                    'name' => $updateValue,
                    'sort' => $sort[$updateValue],
                ]);
            $oldValue = GoodAttrValue::query()
                ->where('good_id', $id)
                ->where('good_attr_id', $key)
                ->get()
                ->pluck('value', 'id')
                ->all();
            $addValue = array_diff($spec[$updateValue], $oldValue);
            $delValue = array_diff($oldValue, $spec[$updateValue]);
            foreach ($addValue as $item) {
                GoodAttrValue::query()
                    ->firstOrCreate([
                        'good_id' => $id,
                        'good_attr_id' => $key,
                        'value' => $item,
                    ]);
            }
            foreach ($delValue as $key1 => $item) {
                GoodAttrValue::query()->where('id', $key1)->where('good_attr_id', $key)->where('good_id', $id)->delete();
            }
        }
        UserGoodsPoster::query()->where('good_id', $id)->delete();
        GoodsList::query()->where('goods_type', GoodsList::TYPE_GOOD)->where('link_id', $id)->update(['sort' => $data['sort']]);
        return redirect()->route('admin.good.spec.edit', ['id' => $id, 'redirect' => $redirect]);
    }

    public function changeSort(Request $request)
    {
        $this->checkAuth('merchant_staff_and_package_sort', 'good');
        $id = $request->input('id');
        $sort = $request->input('sort');
        Good::query()
            ->where('id', $id)
            ->update(['sort' => $sort]);
        return redirect()->back();
    }

    public function status($id)
    {
        // $this->checkAuth('merchant_staff_and_package_upper_and_lower', 'good-upper_and_lower');
        $this->checkAuth(['merchant_staff_up','merchant_staff_down'], ['good_up','good_down']);
        $good = Good::query()->find($id);
        if ($good->status == Good::STATUE_OFF) {
            $good->status = Good::STATUE_ON;
            GoodsList::addData(GoodsList::TYPE_GOOD, $good->id, $good->price, $good->sort, $good->sales_volume, $good->created_at, $good->visitor);
        } else {
            $good->status = Good::STATUE_OFF;
            GoodsList::query()->where('goods_type', GoodsList::TYPE_GOOD)->where('link_id', $id)->delete();
        }
        $good->save();
        return redirect()->back();
    }

    public function editSpec($id, Request $request)
    {
        $this->checkAuth('merchant_staff_and_package_edit', 'good-edit');
        $redirect = $request->input('redirect');
        $good = Good::query()->find($id);
        $attr = GoodAttr::query()->where('good_id', $good->id)->get()->keyBy('id');
        $attrValue = GoodAttrValue::query()->whereIn('good_attr_id', $attr->pluck('id')->all())->get()->groupBy('good_attr_id');
        $spec = GoodSpec::query()->where('good_id', $id)->get()->keyBy('attr_key');
        $data = [[]];
        $attr = $attr->sortBy('id');
        foreach ($attr as $key => $item) {
            if (!is_null($value = $attrValue->get($key))) {
                $val = $value->pluck('value', 'id')->all();
                $data = GoodManager::AttrValueToSpec($data, $val);
            }
        }
        $shopId = $good->shop_id;
        $sidebar = 'goods_detail';
        return view('good.spec', compact('good', 'attr', 'attrValue', 'data', 'spec', 'shopId', 'redirect', 'sidebar'));
    }

    public function updateSpec($id, Request $request)
    {
        $this->checkAuth('merchant_staff_and_package_edit', 'good-edit');
        $good = Good::query()->find($id);
        $redirect = $request->input('redirect', route('admin.good.index', ['shop_id' => $good->shop_id]));
        $stock = $request->input('stock');
        // $displayPrice = $request->input('display_price');
        $price = $request->input('price');
        $prepayPrice = $request->input('prepay_price');
        $level1Rebate = $request->input('level1_rebate');
        $level2Rebate = $request->input('level2_rebate');
        $level3Rebate = $request->input('level3_rebate');
        $level4Rebate = $request->input('level4_rebate');
        $level23Rebate = $request->input('level_2_3_rebate');
        $attr = GoodAttr::query()->where('good_id', $good->id)->get()->keyBy('id');
        $attrValue = GoodAttrValue::query()->where('good_id', $good->id)->get()->keyBy('id');
        $spec = GoodSpec::query()->where('good_id', $id)->get()->keyBy('attr_key');
        $keys = array_keys($stock);
        $oldKeys = $spec->keys()->all();

        $del = array_diff($oldKeys, $keys);
        foreach ($del as $value) {
            GoodSpec::query()
                ->where('good_id', $good->id)
                ->where('attr_key', (string)$value)
                ->delete();
        }
        foreach ($keys as $value) {
            $valueIds = explode(",", $value);
            $param = [];
            foreach ($valueIds as $value1) {
                $tmp = $attrValue->get($value1);
                $attrTmp = $attr->get($tmp->good_attr_id);
                $param[$attrTmp->name] = $tmp->value;
            }
            GoodSpec::query()
                ->updateOrCreate([
                    "good_id" => $id,
                    "attr_key" => $value,
                ], [
                    "param" => $param,
                    'display_price' => $price[$value] * 100,
                    "price" => $price[$value] * 100,
                    "prepay_price" => $prepayPrice[$value] * 100,
                    "stock" => $stock[$value],
                    "level1_rebate" => $level1Rebate[$value] * 100,
                    "level2_rebate" => $level2Rebate[$value] * 100,
                    "level3_rebate" => $level3Rebate[$value] * 100,
                    "level4_rebate" => $level4Rebate[$value] * 100,
                    "level_2_3_rebate" => $level23Rebate[$value] * 100,
                ]);
        }
        return redirect($redirect);
    }

    public function getComment(Request $request)
    {
        $this->checkAuth("merchant_staff_and_package_comment", "good-comment");
        $shopId = $request->input('shop_id');
        $top_category = "comment";
        $goods_id = $request->input('id');

        $comment = Comment::query()
                    ->where('type', Comment::TYPE_GOOD)
                    // ->where('link_id', $goods_id)
                    ->where('shop_id', $shopId)
                    ->orderBy('created_at', 'desc')
                    ->paginate(20);
        $user = User::query()
            ->whereIn('id', $comment->pluck('user_id')->all())
            ->get()
            ->keyBy('id');
        $image = [];

        // 商家回复
        $aCommentChild = Comment::query()
            ->whereIn('pid', $comment->pluck('id')->all())
            ->get(['id','pid','content', 'system_reply_username', 'merchant_reply_username'])
            ->keyBy('pid');

        $comment->map(function ($item) use ($aCommentChild) {
            if (!empty($item->image)) {
                if (gettype($item->image) == "string") {
                    $item->image = json_decode($item->image, true);
                }
                foreach ($item->image as $item1) {
                    $image[] = OSS::instance()->getUrl($item1);
                }
                $item->image = implode($image, ";");
            }
                
            $item->child = !empty($aCommentChild->get($item->id)) ? $aCommentChild->get($item->id) : '';

        });

        $sidebar = 'comment';
        return view('good.comment', compact('comment', 'top_category', 'shopId', 'user', 'sidebar'));
    }

    public function hideComment($id, $is_show)
    {
        $this->authorize('comment-edit');
        Comment::query()
            ->where('id', $id)
            ->where('type', Comment::TYPE_GOOD)
            ->update([
                'is_show' => $is_show,
            ]);
        return redirect()->back();
    }

    public function editRules($id)
    {
        $this->checkAuth('merchant_staff_and_package_edit', 'good-edit');
        $rules = RebateRule::query()
            ->where('type', RebateRule::TYPE_GOOD)
            ->where('link_id', $id)
            ->first();
        if (!is_null($rules)) {
            $rules->level1_rebate = $rules->level1_rebate / 100;
            $rules->level2_rebate = $rules->level2_rebate / 100;
            $rules->level3_rebate = $rules->level3_rebate / 100;
            $rules->level4_rebate = $rules->level4_rebate / 100;
            $rules->level_2_3_rebate = $rules->level_2_3_rebate / 100;
        }

        $form = $this->form(RulesForm::class, [
            'method' => 'POST',
            'url' => route('admin.good.rules.update', ['id' => $id]),
            'model' => $rules,
        ]);
        $shopId = Good::query()->find($id)->shop_id;
        return view('good.form', compact('form', 'shopId'));
    }

    public function updateRules($id)
    {
        $this->checkAuth('merchant_staff_and_package_edit', 'good-edit');
        $form = $this->form(RulesForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $data['level1_rebate'] *= 100;
        $data['level2_rebate'] *= 100;
        $data['level3_rebate'] *= 100;
        $data['level4_rebate'] *= 100;
        $data['level_2_3_rebate'] *= 100;

        RebateRule::query()
            ->updateOrCreate([
                'type' => RebateRule::TYPE_GOOD,
                'link_id' => $id,
            ], $data);
        $shopId = Good::query()->find($id)->shop_id;
        return redirect()->route('admin.good.index', ['shop_id' => $shopId]);
    }

    /**
     * 分类列表
     */
    public function indexCategory(Request $request)
    {
        $this->checkAuth('merchant_staff_good-category','good-category');

        $this->validate($request, [
            'top_category_id'   => 'integer',
            'first_category_id' => 'integer',
            'shop_id'           => 'required|integer',
        ]);

        $shopId = $request->input('shop_id', '');
        $name   = $request->input('name', '');
        $pid    = $request->input('pid', '');

        $shopData = Shop::query()->find($shopId);
        $data = Category::query()
            ->when($name != '', function ($query) use ($name) {
                return $query->where('name', 'like', '%' . $name . "%");
            })
            ->when(!empty($pid), function ($query) use ($pid) {
                return $query->where('pid', $pid);
            })
            ->where('shop_id', $shopId)
            ->whereIn('top_category_id', $shopData->category_ids ?? [])
            ->where('first_category_id', 0)
            ->where([["name","!=","婚纱摄影"],["parent","!=","婚纱摄影"]])
            ->orderBy('sort', 'desc')
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        if ($data) {
            $aParentIds = $data->pluck('id')->all();
            $aCategoryChild = DB::table('categories')
                                ->whereIn('first_category_id', $aParentIds)
                                ->where('deleted_at', null)
                                ->orderBy('sort', 'desc')
                                ->orderBy('created_at', 'desc')
                                ->get(['id','first_category_id','name','sort'])
                                ->all();
            foreach ($data as $k => $v) {
                
                $child = [];
                if ($aCategoryChild) {
                    foreach ($aCategoryChild as $key => $value) {
                        if ($v->id == $value->first_category_id) {
                            $child[] = $value;
                        }
                    }
                }
                $v->child = $child;
            }
        }
        $sidebar = 'category';
        return view('good.category_index', compact('data', 'shopId', 'parent', 'topCategory', 'name', 'sidebar'));
    }

    /**
     * 查询分类
     */
    public function selectCategory(Request $request)
    {
        $this->validate($request, [
            'top_category_id'   => 'required|integer',
            'first_category_id' => 'integer',
            'shop_id'           => 'required|integer',
        ]);

        $top_category_id   = $request->input('top_category_id');
        $first_category_id = $request->input('first_category_id');
        $shop_id           = $request->input('shop_id');

        $result = Category::query()
            ->when(isset($top_category_id), function ($query) use ($top_category_id) {
                return $query->where('top_category_id', $top_category_id);
            })
            ->when(isset($first_category_id), function ($query) use ($first_category_id) {
                return $query->where('first_category_id', $first_category_id);
            })
            ->when(!empty($shop_id), function ($query) use ($shop_id) {
                return $query->where('shop_id', $shop_id);
            })
            ->get(['id', 'name'])
            ->toArray();
        array_unshift($result, ['id' => 0, 'name' => '无']);

        return $result;
    }

    /**
     * 查询二级分类
     */
    public function selectSecondCategory(Request $request)
    {
        $this->validate($request, [
            'top_category_id'   => 'required|integer',
            'first_category_id' => 'integer',
            'shop_id'           => 'required|integer',
        ]);

        $top_category_id   = $request->input('top_category_id');
        $first_category_id = $request->input('first_category_id');
        $shop_id           = $request->input('shop_id');

        $result = Category::query()
            ->when(isset($top_category_id), function ($query) use ($top_category_id) {
                return $query->where('top_category_id', $top_category_id);
            })
            ->when(isset($first_category_id), function ($query) use ($first_category_id) {
                return $query->where('first_category_id', $first_category_id);
            })
            ->when(!empty($shop_id), function ($query) use ($shop_id) {
                return $query->where('shop_id', $shop_id);
            })
            ->get(['id', 'name'])
            ->pluck('name', 'id');

        return $result;
    }

    /**
     * 查询品牌
     */
    public function selectBrand(Request $request)
    {
        $this->validate($request, [
            'pid'     => 'required|integer',
            'shop_id' => 'required|integer',
        ]);

        $pid     = $request->input('pid');
        $shop_id = $request->input('shop_id');

        $result = Brand::query()
            ->when(isset($pid), function ($query) use ($pid) {
                return $query->where('pid', $pid);
            })
            ->when(!empty($shop_id), function ($query) use ($shop_id) {
                return $query->where('shop_id', $shop_id);
            })
            ->get(['id', 'name'])
            ->toArray();
        array_unshift($result, ['id' => 0, 'name' => '无']);

        return $result;
    }

    /**
     * 添加
     */
    public function createCategory(Request $request)
    {
        $this->checkAuth('merchant_staff_category-add','category-add');
        $shopId = $request->input('shop_id');

        $shopData = Shop::query()->find($shopId);
        $topCategory = [0 => '请选择顶级分类'];
        if ($shopData->category_ids) {
            $category = Category::query()->whereIn("id", $shopData->category_ids)->pluck('name', 'id')->all();
            foreach ($category as $key => $value) {
                $topCategory[$key] = $value;
            }
        }
        $form = $this->form(GoodCategoryForm::class, [
            'url' => route('admin.good.category.store', ['shop_id' => $shopId]),
            'method' => 'POST',
        ],[
            'top_category' => $topCategory
        ]);
        return view('good.category_form', compact('form', 'topCategory', 'shopId'));
    }

    /**
     * 提交数据
     */
    public function storeCategory(Request $request)
    {
        $this->checkAuth('merchant_staff_category-add','category-add');
        $shopId = $request->input('shop_id');
        $form = $this->form(GoodCategoryForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $data['shop_id'] = $shopId;

        $data['pid'] = $data['first_category_id'] != 0 ? $data['first_category_id'] : $data['top_category_id'];

        $data['parent'] = Category::query()->find($data['top_category_id'])['name'];

        //唯一判断
        if (Category::query()
            ->where('name', $data['name'])
            ->where('shop_id', $shopId)
            ->where('top_category_id', $data['top_category_id'])
            ->where('first_category_id', $data['first_category_id'])
            ->first()
        ) {
            return redirect()->back()->withErrors("该分类已存在");
        }

        Category::query()->create($data);
        return redirect()->route('admin.good.category', ['shop_id' => $shopId]);
    }

    public function editCategory(Request $request)
    {
        $this->checkAuth('merchant_staff_category-edit','category-edit');
        $id     = $request->input('id');
        $shopId = $request->input('shop_id');

        $category = Category::query()
                        ->where('id', $id)
                        ->first();
        $shopData = Shop::query()->find($shopId);
        $topCategory = [0 => '请选择顶级分类'];
        if ($shopData->category_ids) {
            $categoryData = Category::query()->whereIn("id", $shopData->category_ids)->pluck('name', 'id')->all();
            foreach ($categoryData as $key => $value) {
                $topCategory[$key] = $value;
            }
        }
        $firstCategory = [0 => '无'];
        $firstCategoryData = Category::query()
            ->where('top_category_id', $category->top_category_id)
            ->where('first_category_id', 0)
            ->where('shop_id', $shopId)
            ->pluck('name', 'id')
            ->all();
        if ($firstCategoryData) {
            foreach ($firstCategoryData as $k1 => $v1) {
                $firstCategory[$k1] = $v1;
            }
        }
        $form = $this->form(GoodCategoryForm::class, [
            'url'    => route('admin.good.category.update', ['id' => $category->id, 'shop_id' => $shopId]),
            'method' => 'PUT',
            'model'  => $category
        ],[
            'top_category' => $topCategory,
            'first_category' => $firstCategory
        ]);
        return view('good.category_form', compact('form', 'shopId'));
    }

    public function updateCategory(Request $request)
    {
        $this->checkAuth('merchant_staff_category-edit','category-edit');
        $id = $request->input('id');
        $shopId = $request->input('shop_id');
        $form = $this->form(GoodCategoryForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }

        $data = $form->getFieldValues();
        $data['parent'] = Category::query()->find($data['top_category_id'])['name'];

        //唯一判断
        if (Category::query()
            ->where('id', '<>', $id)
            ->where('shop_id', $shopId)
            ->where('name', $data['name'])
            ->where('top_category_id', $data['top_category_id'])
            ->where('first_category_id', $data['first_category_id'])
            ->first()
        ) {
            return redirect()->back()->withErrors("该分类已存在");
        }

        $category = Category::query()
                        ->where('id', $id)
                        ->first();
        $category->update($data);
        return redirect()->route('admin.good.category', ['shop_id' => $shopId]);
    }

    /**
     * 删除方法
     */
    public function destroyCategory(Request $request)
    {
        $this->checkAuth('merchant_staff_category-delete','category-delete');
        $id = $request->input('id');
        $category = Category::query()
                        ->where('id', $id)
                        ->first();
        $category->delete();
        
        // first_category_id=0, 即删除一级分类 同时删除对应下面的二级分类
        if ($category->first_category_id == 0) {

            $categoryChild = Category::query()->where('first_category_id', $id)->get();
            foreach ($categoryChild as $key => $value) {
                $value->delete();
            }
        }
        
        return redirect()->back();
    }

    /**
     * 排序
     */
    public function changeCategorySort(Request $request)
    {
        $id = $request->input('id');
        $sort = $request->input('sort');
        Category::query()
            ->where('id', $id)
            ->update(['sort' => $sort]);
        return redirect()->back();
    }
}
